package com.clkj.nangang.util;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import com.clkj.nangang.app.CustomApplication;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by Administrator on 2016/8/23.
 */
public class CommonUtil {


    public static String convertHtmlToNormal(String originalHtml)
    {
        return originalHtml.replaceAll("&lt;","<")
                            .replaceAll("&gt;",">")
                            .replaceAll("&nbsp;"," ")
                            .replaceAll("&amp;","&")
                            .replaceAll("&quot;","\"");

    }
    /**
     * 判断一个文件是否是office文件
     *
     * @param fileName
     * @return
     */
    public static boolean validateFileIsOfficeFile(String fileName) {
        // 汉字的正则
        //String   regEx  =  "[\u4E00-\u9FA5]";
        Pattern p = Pattern.compile("^doc$");
        boolean isMath = p.matcher(fileName).matches();

        return isMath;
    }


    /**
     * 判断字符串中没有汉字
     * 如果输入的是没有汉字，则返回true,否则返回false
     *
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean validateStrNotHasHanZi(String str) throws PatternSyntaxException {
        // 汉字的正则
        //String   regEx  =  "[\u4E00-\u9FA5]";
        Pattern p = Pattern.compile("^[^\u4e00-\u9fa5]*$");
        boolean isMath = p.matcher(str).matches();

        return isMath;
    }

    public static String makeHtmlImgFitScreen(String htmltext) {

        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");
        }

        Log.d("VACK", doc.toString());
        return doc.toString();
    }


    /**
     * 在二维码中间添加Logo图案
     */
    public static Bitmap erWeiMaAddLogo(Bitmap erWeiMaBitMap, Bitmap logo) {
        if (erWeiMaBitMap == null) {
            return null;
        }

        if (logo == null) {
            return erWeiMaBitMap;
        }

        //获取图片的宽高
        int srcWidth = erWeiMaBitMap.getWidth();
        int srcHeight = erWeiMaBitMap.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return erWeiMaBitMap;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(erWeiMaBitMap, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }


   /* public static void clearLocalShareInfo()
    {
        CommonUtil.putShareValue(ShareKey.SHARE_KEY_USER_ID,"");
        CommonUtil.putShareValue(ShareKey.SHARE_KEY_USER_NAME,"");
        CommonUtil.putShareValue(ShareKey.SHARE_KEY_IS_LOGIN,false);
        CommonUtil.putShareValue(ShareKey.SHARE_KEY_RONGYUN_TOKEN,"");
    }*/


    //调用拨号键盘
    public static void dialPhoneNumber(String phoneNumber, Context context) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phoneNumber));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }


    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    //判断是否是手机号码
    public static boolean isMobile(String mobile) {

        boolean flag = false;

        if (mobile.length() == 0) {

            return false;

        }

        String[] mobiles = mobile.split(",");

        int len = mobiles.length;

        if (len == 1) {

            return Pattern.matches("^((13[0-9])|(14[5,7,9])|(15[^4,\\D])|(17[0,1,3,5-8])|(18[0-9]))\\d{8}$", mobile);

        } else {

            for (int i = 0; i < len; i++) {

                if (isMobile(mobiles[i])) {

                    flag = true;

                } else {

                    flag = false;

                }

            }

        }

        return flag;

    }


    //格式化json数据变成类型 Object
    public static Object formatJsonToObject2(JsonObject dataObject, String jsonKeyWord, TypeToken aimTypeToken) {
        return new Gson().fromJson(dataObject.get(jsonKeyWord), aimTypeToken.getType());
    }

    //格式化json数据变成类型 list
    public static List formatJsonToObject(JsonObject dataObject, String jsonKeyWord, TypeToken aimTypeToken) {
        return new Gson().fromJson(dataObject.get(jsonKeyWord), aimTypeToken.getType());
    }


    //判断list是否为空
    public static boolean isListNullOrEmpty(List dataList) {

        return dataList == null || dataList.size() == 0 ? true : false;

    }

    //判断两个字符串是否一致
    public static boolean isTwoStrSame(String firstStr, String secondStr, String tip) {
        if (!firstStr.equals(secondStr)) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return false;
        } else {
            return true;
        }
    }


    public static boolean isListNullOrEmpty(List dataList, String tip) {

        if (dataList == null || dataList.size() == 0) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;

        } else {
            return false;
        }


    }

    //判断某一个对象是否为空
    public static boolean isObjectNull(Object object, String tip) {
        if (null == object) {
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEditTextEmpty(EditText editTexes, String tip) {
        if (TextUtils.isEmpty(editTexes.getText().toString())) {
            editTexes.requestFocus();
            ToastUtil.showShort(CustomApplication.getInstance(), tip);
            return true;
        } else {
            return false;
        }
    }

    public static boolean isTextViewEmpty(TextView textView, String tip) {
        if (TextUtils.isEmpty(textView.getText().toString())) {
            if (TextUtils.isEmpty(tip) == false) {
                ToastUtil.showShort(CustomApplication.getInstance(), tip);
            }
            return true;
        } else {
            return false;
        }
    }

    public static void putShareValue(String key, Object value) {
        SPUtils.put(CustomApplication.getInstance(), key, value);
    }

    public static Object getShareValue(String key, Object defaultObject) {
        return SPUtils.get(CustomApplication.getInstance(), key, defaultObject);
    }

    public static void clearAllShareValue() {
        SPUtils.clear(CustomApplication.getInstance());
    }

    //把复杂类型 类对象保存到share
    public static void pubObjToShare(String key, Object value) {
        SPUtils.putObject(CustomApplication.getInstance(), key, value);
    }

    //从share里面获取复杂类型 类对象
    public static <T> T getObjFromShare(String key, Class<T> clazz) {
        return SPUtils.getObject(CustomApplication.getInstance(), key, clazz);
    }


    public static void webViewLoadData(WebView wv, String baseUrl, String data) {
        wv.loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", null);
    }

    /**
     * 获取手机IMEI号
     */
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        String imei = telephonyManager.getDeviceId();

        return imei;
    }


    //初始化webview
    public static void initWebView(WebView webView) {
        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本

        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        //webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式, 将图片调整到合适的大小
        //webSettings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放

        webSettings.setSupportMultipleWindows(true);
        webView.setWebChromeClient(new WebChromeClient());

        webSettings.setAppCacheEnabled(true);//是否使用缓存
        webSettings.setDomStorageEnabled(true);//DOM Storage
/**
 * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
 * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
 *//*
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);*/
    }


    /*//初始化去选择的行业列表
    public static void  initIndustryListToChoose()
    {
        List<List<IndustryChildItem>> childIndustryList = new ArrayList<>();

        List<IndustryChildItem> oneChildIndustryList = new ArrayList<>();
        oneChildIndustryList.add(new IndustryChildItem("计算机软件/硬件",false));
        oneChildIndustryList.add(new IndustryChildItem("计算机系统/维修",false));
        oneChildIndustryList.add(new IndustryChildItem("通信（设备/运营/服务）",false));
        oneChildIndustryList.add(new IndustryChildItem("互联网/电子商务",false));
        oneChildIndustryList.add(new IndustryChildItem("网络游戏",false));
        oneChildIndustryList.add(new IndustryChildItem("电子/半导体/集成电路",false));
        oneChildIndustryList.add(new IndustryChildItem("仪器仪表/工业自动化",false));

        List<IndustryChildItem> twoChildIndustryList = new ArrayList<>();
        twoChildIndustryList.add(new IndustryChildItem("会计/审计",false));
        twoChildIndustryList.add(new IndustryChildItem("金融（投资/证券）",false));
        twoChildIndustryList.add(new IndustryChildItem("金融（银行/保险）",false));

        List<IndustryChildItem> threeChildIndustryList = new ArrayList<>();
        threeChildIndustryList.add(new IndustryChildItem("贸易/进出口",false));
        threeChildIndustryList.add(new IndustryChildItem("批发/零售",false));
        threeChildIndustryList.add(new IndustryChildItem("消费品（食/饮/烟酒）",false));
        threeChildIndustryList.add(new IndustryChildItem("服装/纺织/皮革",false));
        threeChildIndustryList.add(new IndustryChildItem("家具/家电/工艺品/玩具",false));
        threeChildIndustryList.add(new IndustryChildItem("办公用品及设备",false));
        threeChildIndustryList.add(new IndustryChildItem("机械/设备/重工",false));
        threeChildIndustryList.add(new IndustryChildItem("汽车/摩托车/零配件",false));

        List<IndustryChildItem> fourChildIndustryList = new ArrayList<>();
        fourChildIndustryList.add(new IndustryChildItem("制药/生物工程",false));
        fourChildIndustryList.add(new IndustryChildItem("医疗/美容/保健/卫生",false));
        fourChildIndustryList.add(new IndustryChildItem("医疗设备/器械",false));


        List<IndustryChildItem> fiveChildIndustryList = new ArrayList<>();
        fiveChildIndustryList.add(new IndustryChildItem("广告/市场推广",false));
        fiveChildIndustryList.add(new IndustryChildItem("会展/博览",false));
        fiveChildIndustryList.add(new IndustryChildItem("影视/媒体/艺术/出版",false));
        fiveChildIndustryList.add(new IndustryChildItem("印刷/包装/造纸",false));


        List<IndustryChildItem> sixChildIndustryList = new ArrayList<>();
        sixChildIndustryList.add(new IndustryChildItem("房地产开发",false));
        sixChildIndustryList.add(new IndustryChildItem("建筑与工程",false));
        sixChildIndustryList.add(new IndustryChildItem("家居/室内设计/装潢",false));
        sixChildIndustryList.add(new IndustryChildItem("物业管理/商业中心",false));


        List<IndustryChildItem> sevenChildIndustryList = new ArrayList<>();
        sevenChildIndustryList.add(new IndustryChildItem("中介服务/家政服务",false));
        sevenChildIndustryList.add(new IndustryChildItem("专业服务/财会/法律",false));
        sevenChildIndustryList.add(new IndustryChildItem("检测/认证",false));
        sevenChildIndustryList.add(new IndustryChildItem("教育/培训",false));
        sevenChildIndustryList.add(new IndustryChildItem("学术/科研",false));


        List<IndustryChildItem> eightChildIndustryList = new ArrayList<>();
        eightChildIndustryList.add(new IndustryChildItem("餐饮/娱乐/休闲",false));
        eightChildIndustryList.add(new IndustryChildItem("酒店/旅游",false));


        List<IndustryChildItem> nineChildIndustryList = new ArrayList<>();
        nineChildIndustryList.add(new IndustryChildItem("交通/运输/物流",false));
        nineChildIndustryList.add(new IndustryChildItem("航天/航空",false));


        List<IndustryChildItem> tenChildIndustryList = new ArrayList<>();
        tenChildIndustryList.add(new IndustryChildItem("能源（石油/化工/矿产）",false));
        tenChildIndustryList.add(new IndustryChildItem("能源（采掘/冶炼/原材料）",false));
        tenChildIndustryList.add(new IndustryChildItem("电力/水利/新能源",false));


        List<IndustryChildItem> elevenChildIndustryList = new ArrayList<>();
        elevenChildIndustryList.add(new IndustryChildItem("政府部门/事业单位",false));
        elevenChildIndustryList.add(new IndustryChildItem("非盈利机构/行业协会",false));
        elevenChildIndustryList.add(new IndustryChildItem("农业/渔业/林业/牧业",false));


        List<IndustryChildItem> twelevChildIndustryList = new ArrayList<>();
        twelevChildIndustryList.add(new IndustryChildItem("其他行业",false));


        childIndustryList.add(oneChildIndustryList);
        childIndustryList.add(twoChildIndustryList);
        childIndustryList.add(threeChildIndustryList);
        childIndustryList.add(fourChildIndustryList);
        childIndustryList.add(fiveChildIndustryList);
        childIndustryList.add(sixChildIndustryList);
        childIndustryList.add(sevenChildIndustryList);
        childIndustryList.add(eightChildIndustryList);
        childIndustryList.add(nineChildIndustryList);
        childIndustryList.add(tenChildIndustryList);
        childIndustryList.add(elevenChildIndustryList);
        childIndustryList.add(twelevChildIndustryList);

    }*/

}
